package com.imooc.sell.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登陆拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    StringRedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        /* 获取openid*/
        String openid = httpServletRequest.getParameter("openid");
        HttpSession session = httpServletRequest.getSession();
        String sessionId = session.getId();
        String[] patterns = httpServletRequest.getRequestURL().toString().split("/");
        if (!"admin".equals(patterns[patterns.length - 2])) {
            return true;
        }
        /* 验证redis中的登陆信息*/
        String redisSessionId = "";
        try {
            redisSessionId = redisTemplate.opsForValue().get(String.format(openid));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (sessionId.equals(redisSessionId)) {
            return true;
        } else {
            httpServletResponse.sendRedirect("http://localhost:8080/sell/autho/login");
        }
        return false;
    }

    //请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {
    }

    //在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {

    }
}
